package channel

import (
	"errors"
	"github.com/mitchellh/mapstructure"
	"github.com/spf13/cast"
	"hc_server/pkg/request"
	"hc_server/pkg/setting"
	"hc_server/pkg/util"
	"hc_server/routers/models"
	"path/filepath"
	"strings"
)

const (
	papiBaseUrl = "https://papi.lianfutech.cn"
	eapiBaseUrl = "https://eapi.lianfutech.cn"
	Agentno     = "P0001137" //代理商编号
	/*
		● 单次调用接口最多处理10张图片，每张图片大小不得大于2M
	*/
	upload = "/v1/merchant/img/upload" //图片上传
	/*
		● 商户入驻成功后，需进行人工审核，审核结果通过【7.13 商户审核回调】进行通知，请提前联系运营配置商户审核回调地址；
		● 若请求该接口超时或者请求失败，请调用该接口重新入驻；
		● 若请求该接口成功，但是【7.13 商户审核回调】通知审核审核状态为“4-已驳回”，请调用【7.9 商户信息修改】接口修改商户信息；
	*/
	income             = "/v1/merchant/income/income"              //商户入驻
	settleChange       = "/v1/merchant/settle/record/change"       // 商户结算信息修改
	shopNameChange     = "/v1/merchant/shopName/change"            //商户简称信息修改
	merchantRateRange  = "/v1/merchant/rate/range"                 //商户费率范围查询接口
	merchantAuditQuery = "/v1/merchant/audit/query"                //商户审核结果查询
	wechatApprove      = "/v1/wechat/getWechatApproveByMerchantId" //微信认证查询
	wechatAuth         = "/v1/wechat/getWechatAuthByMerchantId"    //微信授权状态查询
	alipayApprove      = "/v1/alipay/getAlipayApproveByMerchantId" //支付宝认证查询
	alipayAuth         = "/v1/alipay/getAlipayAuthByMerchantId"    //支付宝授权状态查询
	deviceBind         = "/v1/deviceResponse/bind/or/unbind"       //设备绑定/解绑
	payUnifyPay        = "/api/v1/pay/unifyPay"                    //统一支付
	barCodePay         = "/api/v1/pay/barCodePay"                  //条码支付
	order              = "/api/v1/pay/order"                       //订单查询
)

// LianImgUpload 图片上传
func LianImgUpload(list []*LianImgUploadParam, merchantId string) error {
	var fileList []interface{}
	for _, img := range list {
		img.FileType = strings.TrimPrefix(filepath.Ext(img.OutFileUrl), ".")
		mapd, err := util.StructToMap(img)
		if err != nil {
			return err
		}
		fileList = append(fileList, mapd)
	}

	data, err := request.QuickRequest(map[string]interface{}{"fileList": fileList}, papiBaseUrl+upload)
	if err != nil {
		return err
	}

	result := cast.ToStringMap(data)
	for _, file := range cast.ToSlice(result["fileList"]) {
		fileMap := cast.ToStringMap(file)
		if cast.ToInt(fileMap["status"]) == 0 {
			return errors.New("图片上传失败")
		}
		//保存联动上传图片
		err = models.LianMerchantUploadAdd(map[string]interface{}{
			"temp_merchant_id": merchantId,
			"file_id":          fileMap["fileId"],
			"remarks":          fileMap["remarks"]})
		if err != nil {
			return err
		}
	}

	return nil
}

// LianIncome 商户入驻
func LianIncome(param *LianIncomeParam) (map[string]interface{}, error) {
	param.AgentId = Agentno

	// 创建一个map用于存放解码后的结果
	var decoded map[string]interface{}

	// 使用mapstructure进行解码
	err := mapstructure.Decode(param, &decoded)
	if err != nil {
		return nil, err
	}

	data, err := request.QuickRequest(decoded, papiBaseUrl+income)
	if err != nil {
		return nil, err
	}

	return cast.ToStringMap(data), nil
}

// LianSettleUpdate 修改商户结算信息
func LianSettleUpdate(param *LianUpdateParam) (map[string]interface{}, error) {
	// 创建一个map用于存放解码后的结果
	var decoded map[string]interface{}

	// 使用mapstructure进行解码
	err := mapstructure.Decode(param, &decoded)
	if err != nil {
		return nil, err
	}

	data, err := request.QuickRequest(decoded, papiBaseUrl+settleChange)
	if err != nil {
		return nil, err
	}

	return cast.ToStringMap(data), nil
}

// LianShopNameUpdate 修改商户简称信息
func LianShopNameUpdate(merchantId, shopName string) (map[string]interface{}, error) {
	// 创建一个map用于存放解码后的结果
	var decoded = make(map[string]interface{})
	decoded["merchantId"] = merchantId
	decoded["shopName"] = shopName

	data, err := request.QuickRequest(decoded, papiBaseUrl+shopNameChange)
	if err != nil {
		return nil, err
	}

	return cast.ToStringMap(data), nil
}

// LianMerchantRateRange 商户费率范围查询接口
func LianMerchantRateRange(merchantId string) (map[string]interface{}, error) {
	var decoded = make(map[string]interface{})
	decoded["merchantId"] = merchantId

	data, err := request.QuickRequest(decoded, papiBaseUrl+merchantRateRange)
	if err != nil {
		return nil, err
	}

	return cast.ToStringMap(data), nil
}

// LianMerchantAuditQuery 商户审核结果查询
func LianMerchantAuditQuery(param *LianMerchantAuditQueryParam) (map[string]interface{}, error) {
	var decoded map[string]interface{}
	err := mapstructure.Decode(param, &decoded)
	if err != nil {
		return nil, err
	}

	data, err := request.QuickRequest(decoded, papiBaseUrl+merchantAuditQuery)
	if err != nil {
		return nil, err
	}

	return cast.ToStringMap(data), nil
}

// LianWechatApprove 微信认证查询
func LianWechatApprove(merchantId string) (map[string]interface{}, error) {
	var decoded = make(map[string]interface{})
	decoded["merchantId"] = merchantId

	data, err := request.QuickRequest(decoded, papiBaseUrl+wechatApprove)
	if err != nil {
		return nil, err
	}

	return cast.ToStringMap(data), nil
}

// LianWechatAuth 微信授权状态查询
func LianWechatAuth(merchantId string) (map[string]interface{}, error) {
	var decoded = make(map[string]interface{})
	decoded["merchantId"] = merchantId

	data, err := request.QuickRequest(decoded, papiBaseUrl+wechatAuth)
	if err != nil {
		return nil, err
	}

	return cast.ToStringMap(data), nil
}

// LianAlipayApprove 支付宝认证查询
func LianAlipayApprove(merchantId string) (map[string]interface{}, error) {
	var decoded = make(map[string]interface{})
	decoded["merchantId"] = merchantId

	data, err := request.QuickRequest(decoded, papiBaseUrl+alipayApprove)
	if err != nil {
		return nil, err
	}

	return cast.ToStringMap(data), nil
}

// LianAlipayAuth 支付宝授权状态查询
func LianAlipayAuth(merchantId string) (map[string]interface{}, error) {
	var decoded = make(map[string]interface{})
	decoded["merchantId"] = merchantId

	data, err := request.QuickRequest(decoded, papiBaseUrl+alipayAuth)
	if err != nil {
		return nil, err
	}

	return cast.ToStringMap(data), nil
}

// LianDeviceBind 设备绑定/解绑
func LianDeviceBind(param *LianDeviceBindParam) (map[string]interface{}, error) {
	var decoded map[string]interface{}
	err := mapstructure.Decode(param, &decoded)
	if err != nil {
		return nil, err
	}

	data, err := request.QuickRequest(decoded, papiBaseUrl+deviceBind)
	if err != nil {
		return nil, err
	}

	return cast.ToStringMap(data), nil
}

// LianUnifyPay 统一支付
func LianUnifyPay(param *PayUnifyPayParam) (map[string]interface{}, error) {
	param.NotifyUrl = setting.GetConfig().App.PrefixUrl + "/api/v1/transaction/lian/notify"
	var decoded map[string]interface{}
	err := mapstructure.Decode(param, &decoded)
	if err != nil {
		return nil, err
	}

	data, err := request.QuickRequest(decoded, papiBaseUrl+payUnifyPay)
	if err != nil {
		return nil, err
	}

	return cast.ToStringMap(data), nil
}

// LianBarCodePay 条码支付
func LianBarCodePay(param *PayBarCodePayParam) (map[string]interface{}, error) {
	var decoded map[string]interface{}
	err := mapstructure.Decode(param, &decoded)
	if err != nil {
		return nil, err
	}

	data, err := request.QuickRequest(decoded, papiBaseUrl+barCodePay)
	if err != nil {
		return nil, err
	}

	return cast.ToStringMap(data), nil
}

// LianOrder 订单查询
func LianOrder(param *OrderParam) (map[string]interface{}, error) {
	var decoded map[string]interface{}
	err := mapstructure.Decode(param, &decoded)
	if err != nil {
		return nil, err
	}

	data, err := request.QuickRequest(decoded, papiBaseUrl+order)
	if err != nil {
		return nil, err
	}

	return cast.ToStringMap(data), nil
}
